package cn.mybatishelper.entity.mybatis;

import cn.mybatishelper.entity.database.ColumnEntity;
import cn.mybatishelper.entity.database.DatabaseEntity;

/**
 * mybatis 插入类型元素，即<insert id="xx">类型
 * 用户生成插入映射语句
 *
 * @author GameKing
 */
public class InsertMybatisElement extends MybatisElement {
    /**
     * 元素的标签，在此为insert类型  *
     */
    private static final String type = "insert";

    public InsertMybatisElement() {
        super("insert", null, true);
    }

    public InsertMybatisElement(String id, DatabaseEntity databaseEntity, boolean isMethod) {
        super(id, databaseEntity, isMethod);
    }

    @Override
    public String toXmlString() {
        if (!validateDatabaseEntity()) {
            return null;
        }
        if (!validateElement()) {
            return null;
        }

        StringBuilder stringBuilder = new StringBuilder("\n");
        stringBuilder.append("\t");
        stringBuilder.append("<insert id=\"" + this.id + "\">");
        stringBuilder.append("\n");
        stringBuilder.append("\t\t");
        stringBuilder.append("INSERT INTO " + databaseEntity.getTableName() + "(");
        stringBuilder.append("\n");
        stringBuilder.append("\t\t\t");
        stringBuilder.append("<include refid=\'" + BaseColumnElement.id + "\'/>");
        stringBuilder.append("\n");
        stringBuilder.append("\t\t");
        stringBuilder.append(")VALUES(");
        for (int i = 0; i < databaseEntity.getColumnList().size(); i++) {
            ColumnEntity column = databaseEntity.getColumnList().get(i);
            stringBuilder.append("\n");
            stringBuilder.append("\t\t\t");
            stringBuilder.append("#{" + column.getPropertyName() + ",jdbcType=" + column.getJdbcType() + "}");
            if (i < databaseEntity.getColumnList().size() - 1) {
                stringBuilder.append(",");
            }
        }
        stringBuilder.append("\n");
        stringBuilder.append("\t\t");
        stringBuilder.append(")");
        stringBuilder.append("\n");
        stringBuilder.append("\t");
        stringBuilder.append("</insert>");

        return stringBuilder.toString();
    }


    @Override
    public String toCodeString() {
        if (!validateElement()) {
            return null;
        }

        StringBuilder xmlStrBuffer = new StringBuilder("\n\t");
        xmlStrBuffer.append("public Long " + this.id + "(" + databaseEntity.getObjectName() + " entity);");
        xmlStrBuffer.append("\n");
        return xmlStrBuffer.toString();
    }

    /**
     * *****************************get/set方法*****************************************
     */
    public String getType() {
        return type;
    }

}
